package com.yunban.project.api.text_check.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.api.text_check.domain.UserCorrectionCharLimit;
import com.yunban.project.api.text_check.mapper.UserCorrectionCharLimitMapper;
import com.yunban.project.api.text_check.service.UserCorrectionCharLimitService;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author: lijiajun
 * @date: 2025-02-18
 * @version: 1.0
 */
@Service
public class UserCorrectionCharLimitServiceImpl extends ServiceImpl<UserCorrectionCharLimitMapper, UserCorrectionCharLimit> implements UserCorrectionCharLimitService {
    @Override
    public UserCorrectionCharLimit findByUserId(long userId) {
        LambdaQueryWrapper<UserCorrectionCharLimit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCorrectionCharLimit::getUserId, userId);
        UserCorrectionCharLimit r = this.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(r)) {
            throw new BusinessException("暂未配置纠错服务的使用次数，请联系管理员!");
        }
        return r;
    }

    @Override
    public void useCount(long userId, int charLength) {
        if (charLength <= 0) {
            return;
        }
        UserCorrectionCharLimit r = this.findByUserId(userId);
        // 判断是否超出限制
        if (r.getUsedCharLimit() + charLength > r.getTotalCharLimit()) {
            throw new BusinessException("超出纠错服务使用次数限制，请联系管理员!");
        }
        // update x t set t.used_char_limit = t.used_char_limit + charLength where t.user_id = userId and t.total_char_limit >= t.used_char_limit + charLength
        LambdaUpdateWrapper<UserCorrectionCharLimit> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("used_char_limit = used_char_limit + " + charLength);
        updateWrapper.eq(UserCorrectionCharLimit::getUserId, userId);
        updateWrapper.ge(UserCorrectionCharLimit::getTotalCharLimit, r.getUsedCharLimit() + charLength);
        if (!this.update(updateWrapper)) {
            throw new BusinessException("超出纠错服务使用次数限制，请联系管理员!");
        }
    }
}
